package nero.yncc.com.createart.activity;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.drawable.Icon;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import nero.yncc.com.createart.R;
import nero.yncc.com.createart.adapter.AdapterIndexChangjingList;
import nero.yncc.com.createart.base.BaseActivity;
import nero.yncc.com.createart.base.Constants;
import nero.yncc.com.createart.bean.BeanChangjingAttr;
import nero.yncc.com.createart.bean.ChangjingBean;
import nero.yncc.com.createart.custom.IconView;
import nero.yncc.com.createart.utils.ArrayUtils;
import nero.yncc.com.createart.utils.HttpUtils;
import nero.yncc.com.createart.utils.LIstPopUtil;
import nero.yncc.com.createart.utils.ShopCarUtil;
import nero.yncc.com.createart.utils.TextUtil;

import static android.view.View.GONE;

/**
 * Created by nero on 17-6-26.
 */
@ContentView(R.layout.activity_search_changjing)
public class ActivitySearchChangjing extends BaseActivity {

    @ViewInject(R.id.rl_style)
    RelativeLayout rl_style;
    @ViewInject(R.id.rl_space)
    RelativeLayout rl_space;
    @ViewInject(R.id.rl_house_type)
    RelativeLayout rl_house_type;

    @ViewInject(R.id.icon_style)
    IconView icon_style;
    @ViewInject(R.id.icon_space)
    IconView icon_space;
    @ViewInject(R.id.icon_homestyle)
    IconView icon_homestyle;
    @ViewInject(R.id.et_search)
    EditText et_search;
    @ViewInject(R.id.icon_back)
    IconView icon_back;
    @ViewInject(R.id.ll_nodata)
    LinearLayout ll_nodata;

    @ViewInject(R.id.pl_list)
    PullToRefreshListView pl_list;
    @ViewInject(R.id.tv_num)
    TextView tv_num;
    @ViewInject(R.id.rl_shopcar)
    RelativeLayout rl_shopcar;


    LIstPopUtil lIstPopUtil_style;
    LIstPopUtil lIstPopUtil_space;
    LIstPopUtil lIstPopUtil_housetype;

    ArrayList<String> arrayList_space;
    ArrayList<BeanChangjingAttr.BeanChangjingIn> arrayList_style;
    ArrayList<String> arrayList_style_str;
    ArrayList<BeanChangjingAttr.BeanChangjingIn> arrayList_housetype;
    ArrayList<String> arrayList_housetype_str;

    PopupWindow.OnDismissListener dismissListener_style;
    PopupWindow.OnDismissListener dismissListener_space;
    PopupWindow.OnDismissListener dismissListener_housetype;
//

    //场景套餐
    ArrayList<ChangjingBean> arrayList_changjing;
    AdapterIndexChangjingList adapterIndexChangjing;

    Timer timer_search_keyword = new Timer();

    @Override
    protected void initView() {
        super.initView();

        setPullToRefreshListView(pl_list);
        arrayList_style_str = new ArrayList<>();
        arrayList_style = new ArrayList<>();
        arrayList_housetype = new ArrayList<>();
        arrayList_housetype_str = new ArrayList<>();
        arrayList_space = new ArrayList<>();


    }

    @Override
    protected void initData() {
        super.initData();


        lIstPopUtil_style = new LIstPopUtil(mContext, arrayList_style_str, new LIstPopUtil.OnItemClickListener() {
            @Override
            public void Click(int position) {
                lIstPopUtil_style.dismiss();
                fengge = arrayList_style.get(position).getId();
                if (fengge.equals("-1")) {
                    fengge = "";
                }
                pl_list.setRefreshing(true);
            }
        });
        lIstPopUtil_space = new LIstPopUtil(mContext, arrayList_space, new LIstPopUtil.OnItemClickListener() {
            @Override
            public void Click(int position) {
                lIstPopUtil_space.dismiss();
                mianji = arrayList_space.get(position);
                if (mianji.equals("全部")) {
                    mianji = "";
                }
                pl_list.setRefreshing(true);
            }
        });
        lIstPopUtil_housetype = new LIstPopUtil(mContext, arrayList_housetype_str, new LIstPopUtil.OnItemClickListener() {
            @Override
            public void Click(int position) {
                lIstPopUtil_housetype.dismiss();
                huxing = arrayList_housetype.get(position).getId();
                if (huxing.equals("-1")) {
                    huxing = "";
                }
                pl_list.setRefreshing(true);
            }
        });

        //测试数据
        arrayList_space.add("全部");
        arrayList_space.add("0~100");
        arrayList_space.add("100~200");
        arrayList_space.add("200~300");
//        arrayList_space.add(">400");
        lIstPopUtil_space.flush();


        //max 3  场景套餐
        arrayList_changjing = new ArrayList<>();
        adapterIndexChangjing = new AdapterIndexChangjingList(mContext, arrayList_changjing);
        LinearLayoutManager llm2 = new LinearLayoutManager(mContext);
        llm2.setOrientation(LinearLayoutManager.VERTICAL);

        adapterIndexChangjing.notifyDataSetChanged();

        dismissListener_style = new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                trunAnimationOff(icon_style);
            }
        };

        dismissListener_space = new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                trunAnimationOff(icon_space);
            }
        };

        dismissListener_housetype = new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                trunAnimationOff(icon_homestyle);
            }
        };

        pl_list.setAdapter(adapterIndexChangjing);

        HttpUtils.get(this, Constants.API_CHANGJING_ATTR, new HashMap<String, String>(), BeanChangjingAttr.class, HttpUtils.TYPE_OBJECT, new HttpUtils.HttpCallback() {
            @Override
            public void success(String msg, Object json) {
                BeanChangjingAttr bean = (BeanChangjingAttr) json;
                ArrayUtils.copy(bean.getFengge_list(), arrayList_style, true);
                arrayList_style.add(0, new BeanChangjingAttr.BeanChangjingIn("-1", "全部"));
                ArrayUtils.copy(bean.getHuxing_list(), arrayList_housetype, true);
                arrayList_housetype.add(0, new BeanChangjingAttr.BeanChangjingIn("-1", "全部"));

                for (BeanChangjingAttr.BeanChangjingIn beanin : arrayList_style) {
                    arrayList_style_str.add(beanin.getName());
                }
                for (BeanChangjingAttr.BeanChangjingIn beanin : arrayList_housetype) {
                    arrayList_housetype_str.add(beanin.getName());
                }


                lIstPopUtil_style.flush();
                lIstPopUtil_housetype.flush();
            }

            @Override
            public void fail(String failMsg) {

            }
        });

        ShopCarUtil.getShopCarNum(this, userBean, new ShopCarUtil.ShopCarGetListener() {
            @Override
            public void success(String num) {
                tv_num.setText(num);
            }

            @Override
            public void fail(String num) {
                tv_num.setVisibility(GONE);
            }
        });
    }

    @Override
    protected void getHttpData() {
        super.getHttpData();
    }

    int pageSize = 10;
    int page = 1;
    String fengge = "", mianji = "", huxing = "", keyword = "";
    boolean canLoad = true;

    @Override
    protected void getData() {
        Log.e("123", "获取卡");
        super.getData();
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("pagesize", pageSize + "");
        hashMap.put("pageindex", page + "");
        hashMap.put("fengge", fengge + "");
        hashMap.put("mianji", mianji + "");
        hashMap.put("huxing", huxing + "");
        hashMap.put("keyword", keyword + "");

        HttpUtils.get(this, Constants.API_CHANGJING, hashMap, null, HttpUtils.TYPE_NOTHING, new HttpUtils.HttpCallback() {
            @Override
            public void success(String msg, Object json) {
                try {
                    JSONObject jsonObject = new JSONObject(json.toString());
                    JSONArray jsonArray = jsonObject.getJSONArray("list");
                    if (!canLoad) {
                        pl_list.onRefreshComplete();
                        showToast("没有更多内容啦");
                        return;
                    }
                    if (jsonArray.length() < pageSize) {
                        canLoad = false;
                    }
                    for (int a = 0; a < jsonArray.length(); a++) {
                        arrayList_changjing.add(JSON.parseObject(jsonArray.getString(a), ChangjingBean.class));
                    }
                    adapterIndexChangjing.notifyDataSetChanged();
                    if (arrayList_changjing.size() == 0) {
                        ll_nodata.setVisibility(View.VISIBLE);
                        pl_list.setVisibility(GONE);
                    } else {
                        ll_nodata.setVisibility(GONE);
                        pl_list.setVisibility(View.VISIBLE);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    pl_list.onRefreshComplete();
                }
            }

            @Override
            public void fail(String failMsg) {
                showToast(failMsg);
                pl_list.onRefreshComplete();
            }
        });

    }

    @Override
    protected void initListener() {
        super.initListener();
        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                timer_search_keyword.cancel();
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(final Editable editable) {


                timer_search_keyword = new Timer();
                timer_search_keyword.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                keyword = editable.toString();
                                pl_list.setRefreshing(true);
                            }
                        });

                    }
                }, 600);
            }
        });
        rl_style.setOnClickListener(this);
        rl_space.setOnClickListener(this);
        rl_house_type.setOnClickListener(this);
        pl_list.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {

                page = 1;
                canLoad = true;
                arrayList_changjing.clear();
                getData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                page++;
                getData();
            }
        });
        pl_list.setRefreshing(true);

        et_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEARCH) {
                    keyword = et_search.getText().toString();
                    pl_list.setRefreshing(true);
                }
                return false;
            }
        });
        icon_back.setOnClickListener(this);
        rl_shopcar.setOnClickListener(this );
    }

    @Override
    protected void doClick(int id) {
        super.doClick(id);
        switch (id) {
            case R.id.rl_style:
                showPop(POP_STYLE);
                break;
            case R.id.rl_space:
                showPop(POP_SPACE);
                break;
            case R.id.rl_house_type:
                showPop(POP_HOUSETYPE);
                break;
            case R.id.icon_back:
                finish();
                break;
            case R.id.rl_shopcar:
                startActivity(new Intent(mContext,ActivityShopcar.class));
                break;
        }
    }

    private static final int POP_STYLE = 1, POP_SPACE = 2, POP_HOUSETYPE = 3;

    boolean show_style;

    private void showPop(int id) {
        lIstPopUtil_style.dismiss();
        lIstPopUtil_space.dismiss();
        lIstPopUtil_housetype.dismiss();

        switch (id) {
            case POP_STYLE:

                show_style = true;
                lIstPopUtil_style.show(rl_style, dismissListener_style);
                trunAnimation(icon_style);
                break;
            case POP_SPACE:
                if (lIstPopUtil_space.isShowing()) {
                    lIstPopUtil_space.dismiss();
                } else {
                    lIstPopUtil_space.show(rl_space, dismissListener_space);
                }
                trunAnimation(icon_space);
                break;
            case POP_HOUSETYPE:
                if (lIstPopUtil_housetype.isShowing()) {
                    lIstPopUtil_housetype.dismiss();
                } else {
                    lIstPopUtil_housetype.show(rl_house_type, dismissListener_housetype);
                }
                trunAnimation(icon_homestyle);
                break;
        }
    }

    private void trunAnimation(View view) {
        ObjectAnimator animator = ObjectAnimator.ofFloat(view, "rotation", 0f, 180f);
        animator.setDuration(200);
        animator.start();
    }

    private void trunAnimationOff(View view) {
        ObjectAnimator animator = ObjectAnimator.ofFloat(view, "rotation", 180f, 0);
        animator.setDuration(200);
        animator.start();
    }
}
